<?php
// +----------------------------------------------------------------------
// | 小牛Admin
// +----------------------------------------------------------------------
// | Website: www.xnadmin.cn
// +----------------------------------------------------------------------
// | Author: dav <85168163@qq.com>
// +----------------------------------------------------------------------

namespace app\common\controller;

use app\common\model\UserModel;
use think\facade\Session;
use think\facade\View;

class IndexBase extends Base
{
    #需token认证的操作
    protected $needAuth = [];

    #不需token认证的操作
    protected $noAuth = [];

    #用户ID
    public $uid=0;

    public function initialize()
    {
        $action = $this->request->action();
        if( in_array($action,$this->needAuth) || (isset($this->needAuth[0])&&$this->needAuth[0]=='*') && !in_array($action,$this->noAuth) )
        {
            if( !$this->isLogin() ) {
                $this->redirect(url('login/login'));
            }
        }

        if( $this->isLogin() ) {
            $user = $this->getUser();
            $this->uid = $user['id'];
        }

        View::assign('user', $user);
        View::assign('action', $action);
        View::assign('controller', strtolower($this->request->controller()));
    }
    /**
     * 是否已经登录
     * @return bool
     */
    protected function isLogin()
    {
        return Session::get('user') ? true : false;
    }

    /**
     * 当前用户
     * @return array
     */
    protected function getUser()
    {

        if( $this->isLogin() ) {
            $uid = Session::get('user.id');
            $user = (new UserModel)->find($uid);
            if( $user ) {
                return $user->hidden(['password','salt']);
            } else {
                return [];
            }
        }
        return [];
    }
}
